package Servlet;

import Bean.Flight;
import Service.AircraftService;
import Service.FlightService;
import Utils.DataUtil;
import com.sun.net.httpserver.HttpPrincipal;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 张
 * Date: 2025-03-14
 * Time: 13:43
 */
//录入航班信息
@WebServlet("/AddFlightServlet")
public class AddFlightServlet extends HttpServlet {
    private AircraftService aircraftService = new AircraftService();
    private FlightService flightService = new FlightService();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=utf8");
        String flightId = req.getParameter("flightId");
        String aircraftId = req.getParameter("aircraftId");
        //时间的格式 2025-03-14T17:47
        String departureTime = req.getParameter("departureTime");
        String arrivalTime = req.getParameter("arrivalTime");
        String origin = req.getParameter("origin");
        String destination = req.getParameter("destination");
        Double price= Double.parseDouble(req.getParameter("price"));
        //先查询是有编号为 aircraftId 的飞机
        int ret = aircraftService.selectByAircraftId(aircraftId);
        if(ret == 0) {
            req.setAttribute("status", "error");
            req.setAttribute("message", "修改后的飞机型号不存在");
            req.setAttribute("redirectUrl", "flight_insert.jsp");
            req.setAttribute("waitSeconds", 2);
            req.getRequestDispatcher("skip.jsp").forward(req,resp);
        }
        Flight flight = new Flight();
        flight.setFlightId(flightId);
        flight.setAircraftId(aircraftId);
        flight.setOrigin(origin);
        flight.setDestination(destination);
        flight.setPrice(price);
        flight.setArrivalTime(DataUtil.getData1(arrivalTime));
        flight.setDepartureTime(DataUtil.getData1(departureTime));
        System.out.println("[AddFlightServlet] : " + flight.toString());
        boolean ok = flightService.insert(flight);
        if(!ok) {
            req.setAttribute("status", "error");
            req.setAttribute("message", "录入失败");
            req.setAttribute("redirectUrl", "flight_insert.jsp");
            req.setAttribute("waitSeconds", 2);
            req.getRequestDispatcher("skip.jsp").forward(req,resp);
        }
        req.getRequestDispatcher("FlightsServlet?pageNo=1").forward(req,resp);
    }
}
